package com.diandi.signature.service.impl.signatureca;

import com.diandi.signature.bean.cainfo.SignatureCAInfo;
import com.diandi.signature.enums.fdd.ReturnCode;
import com.diandi.signature.enums.platfrom.CAInfoStatus;
import com.diandi.signature.enums.platfrom.InterfactType;
import com.diandi.signature.fddtools.FddUtil;
import com.diandi.signature.manager.CAInfo.SignatureCAManager;

import com.diandi.signature.properties.FddProperties;
import com.diandi.signature.properties.SignatureProperties;
import com.diandi.signature.sign.Tools;
import com.diandi.signature.signatureca.SignatureCAService;
import com.diandi.signature.url.DateUtil;
import com.diandi.signature.url.GsonUtil;
import com.diandi.signature.utils.CheckParams;
import com.diandi.signature.utils.SignatureBaseParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 个人CA认证信息申请服务接口
* @author mwz
* @create 2017-08-23 14:00
* @version V1.0.0
*/
@Service
public class SignatureCAServiceImpl implements SignatureCAService {

    private static Logger logger = LoggerFactory.getLogger(SignatureCAServiceImpl.class);
    /**
     * 签章通道-法大大
     */
    @Autowired
    private FddProperties fddProperties;

    @Autowired
    private SignatureCAManager signatureCAManager;



    @Autowired
    private SignatureProperties signatureProperties;


    /**
     * CA认证
     * @param request
     * @return
     */
    @Override
    public Map<String, String> createCA(HttpServletRequest request, String tradeNo) {

        /**
         * 1.1 验证业务端签名信息的正确性
         */
        Map<String, String> returnMap = new HashMap<String, String>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
//        Map<String, String> params = Tools.checkSign(request, fddProperties, signatureProperties, "platform");
        Map<String, String> params = Tools.getParameterMap(request, false);
        if (params.containsKey("error")) {
            returnMap = Tools.createCAReturnParams(ReturnCode.err_9001, ReturnCode.err_9001.getMsg(), params.get("error"));
            return returnMap;
        }
        /** 2.1 校验参数是否正确 **/
        try {
            /**
             * 4.1 查询CA信息，不存在就插入数据
             */
            String userId = params.get("userId");
            String passCode = params.get("passCode");
            queryMap.put("userId", userId);
            queryMap.put("passCode", passCode);
            queryMap.put("phone", params.get("phone"));
            queryMap.put("status", CAInfoStatus.成功.getStatus());
            if (params.containsKey("customerId") && StringUtils.isNotBlank(params.get("customerId"))){
                queryMap.put("customerId", params.get("customerId"));
            }
            SignatureCAInfo signatureCAInfo = signatureCAManager.getSignatureCAInfoByCode( queryMap );
            if( signatureCAInfo != null ){
                //用户已做CA认证，直接返回原认证信息
                returnMap.put("code", "1000");
                returnMap.put("customer_id", signatureCAInfo.getSignatureCustomerId());
                returnMap.put("msg", "客户已存在,证书申请成功");
                return returnMap;
            }

            //检查是否包含customerId信息，如果有直接插入数据库，并返回
            if (params.containsKey("customerId") && StringUtils.isNotBlank(params.get("customerId"))){
                params.put("status", String.valueOf(CAInfoStatus.成功.getStatus()));
                signatureCAManager.insertCAInfo(params);
            }

            params.put( "inMsg",Tools.createLinkString( params,false ) );

            /**
             * 5.1 查询渠道信息，根据渠道消息选择相应的发送渠道。
             */

            /**
             * 5.1  向三方通道发送消息,先记录报文信息
             */

            params.put("InterfaceType", String.valueOf(InterfactType.CA认证.getValue()));
            signatureCAManager.insertRtnPkgMsgData( params );
            //mongoService.insert("fddCa", "", params, tradeNo, Long.parseLong(params.get("userId")), "", "请求报文");

            returnMap = SendMsgToSignature(signatureCAInfo, params);

            /**
             * 6.1 更新三方返回消息
             */
            params.put("InterfaceType", String.valueOf(InterfactType.CA认证.getValue()));
            signatureCAManager.updateRtnPkgMsgData( params ,returnMap );

            //更改用户ca信息表，将customerid落库
            if (returnMap.containsKey("customer_id") && StringUtils.isNotBlank(returnMap.get("customer_id"))){
                Map<String, String> caInfoMap = new HashMap<String, String>();
                caInfoMap.put("customerId", returnMap.get("customer_id"));
                caInfoMap.put("status", String.valueOf(CAInfoStatus.成功.getStatus()));
                caInfoMap.put("phone", params.get("phone"));
                caInfoMap.put("userId", params.get("userId"));
                caInfoMap.put("passCode", passCode);
                caInfoMap.put("customerName", params.get("customerName"));
                if (params.containsKey("email") && StringUtils.isNotBlank(params.get("email"))){
                    caInfoMap.put("email", params.get("email"));
                }
                signatureCAManager.insertCAInfo(caInfoMap);
            }
           // mongoService.insert("fddCa", returnMap.toString(), params, tradeNo, Long.parseLong(params.get("userId")), returnMap.get("msg"), "应答报文");
        }catch (Exception e){
            e.printStackTrace();
            returnMap = Tools.createCAReturnParams(ReturnCode.err, null, null);
            return returnMap;
        }
        return returnMap;
    }


    /**
     * 查询CA认证信息
     * @param request
     * @return
     */
    @Override
    public Map<String, String> queryCAInfo(HttpServletRequest request) {

        /**
         * 1.1 验证业务端签名信息的正确性
         */
        Map<String, String> returnMap = new HashMap<String, String>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
//        Map<String, String> params = Tools.checkSign(request, fddProperties, signatureProperties, "platform");
        Map<String, String> params = Tools.getParameterMap(request, false);
        if (params.containsKey("error")) {
            returnMap = Tools.createReturnParams(ReturnCode.err_9001, ReturnCode.err_9001.getMsg(), params.get("error"));
            return returnMap;
        }

        /**
         * 2.1 校验参数是否正确
         */
        returnMap = CheckParams.checkParamsIsExist(params, "userId", "passCode");
        if (null != returnMap && !returnMap.isEmpty()) {
            return returnMap;
        }

        /**
         * 4.1 查询CA信息
         */
        queryMap.put("userId", params.get("userId"));
        queryMap.put("passCode", params.get("passCode"));
        queryMap.put("phone", params.get("phone"));
        queryMap.put("status", CAInfoStatus.成功.getStatus());
        SignatureCAInfo signatureCAInfo = signatureCAManager.getSignatureCAInfoByCode( queryMap );
        if (null != signatureCAInfo) {
//            returnMap = MapTransf.objrctTransfMap(signatureCAInfo);
            returnMap.put("status", String.valueOf(signatureCAInfo.getStatus()));
            returnMap.put("signatureCustomerId", signatureCAInfo.getSignatureCustomerId());
            returnMap.put("phone", signatureCAInfo.getPhone());
            returnMap.put("userName", signatureCAInfo.getUserName());
            returnMap.put("email", signatureCAInfo.getEmail());
            returnMap.put("passCode", signatureCAInfo.getPassCode());
            returnMap.put("userId", String.valueOf(signatureCAInfo.getUserId()));
            returnMap.put("verifyDate", DateUtil.getFmtDate(signatureCAInfo.getUpdateTime()));
            returnMap.putAll(Tools.createReturnParams(ReturnCode.ok, ReturnCode.ok.getMsg(), null));
        } else {
            returnMap = Tools.createReturnParams(ReturnCode.CA_3002, "", null);
        }
        return returnMap;
    }

    /**
     * 发送到第三方签章系统
     * @param signatureCAInfo
     * @param params
     * @return
     */
    public Map<String, String> SendMsgToSignature( SignatureCAInfo signatureCAInfo, Map<String, String> params) {
        Map<String, String> returnMap = new HashMap<String, String>();
        /**
         * 1.1 封装基础参数
         */
        try {
                Map<String, String> resultMap = SignatureBaseParams.getFddBaseParams( fddProperties );
                //封装业务参数

                /**
                 * 2.1 封装基础参数
                 */
//                resultMap.put("customer_name", params.get("customerName"));
//                if (params.containsKey("email") && StringUtils.isNotBlank(params.get("email"))){
//                    resultMap.put("email",params.get("email"));
//                }
                String phone = params.get("phone");
//                String idcard = params.get("idCard");
//                String app_secret = fddProperties.getAppSecert();
//                String id_mobile = FddEncryptTool.encrypt(idcard + "|" + phone, app_secret);
//                resultMap.put("id_mobile",id_mobile);
//                resultMap.put("_input_charset", signatureProperties.getCharset());

                 //进行HTTP请求
                String result = FddUtil.invokeSyncPersonAuto(params.get("customerName"), params.get("idCard"), phone);

                //处理返回结果
                returnMap = GsonUtil.fronJson2Map(result);
//                params.put("syncRtnMsgPlatfrom",Tools.createLinkString(returnMap,false));
//                params.put("syncRtnMsgPayment", URLDecoder.decode(result, signatureProperties.getCharset()));
                //记录数据库
//                 signatureCAManager.receiveSignatureSaveData(signatureCAInfo,params);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            returnMap = Tools.createCAReturnParams(ReturnCode.err_9000, null,null);
        }
        return returnMap;
    }
}